package com.haiermzj.server;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.haiermzj.server.eventbus.MessageEvent;
import com.haiermzj.server.interfaces.ClientReadDataSuccess;
import com.haiermzj.server.services.MyServerSocketService;
import com.haiermzj.server.utils.MyDateUtil;
import com.mob.mobapi.API;
import com.mob.mobapi.APICallback;
import com.mob.mobapi.MobAPI;
import com.mob.mobapi.apis.Weather;
import com.mob.tools.utils.ResHelper;
import com.rock.qrcodelibrary.CaptureActivity;
import com.rock.qrcodelibrary.VideoActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements ClientReadDataSuccess, APICallback {

    private static final int HANDLER_MSG_UPDATE = 0;
    private static final String TAG = MainActivity.class.getCanonicalName();
    private String s;
    private static final int REQUEST_PERMISSION_CAMERA_CODE = 1;
    public static final String[] permissions = new String[]{Manifest.permission.CAMERA};
    private TextView tianqiTv;
    private long currentTime;
    private TextView timeMdTv;
    private TextView timeHhTv;
    private TextView timeMmTv;
    private TextView weekTv;
    private TextView helloworldTv;
    private int nowHInt;
    Timer mTimer = new Timer();
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_MSG_UPDATE:
                    update();
                    break;
            }
            super.handleMessage(msg);
        }

        private void update() {
//更新UI，每分钟
            Log.e(TAG, "update: " + "更新");
            setDate();
        }
    };
    private TextView nongLiTv;
    private com.mob.mobapi.apis.Calendar calendarApi;
    private ImageView weatherImg;

    @TargetApi(Build.VERSION_CODES.M)
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestCameraPermission() {
        requestPermissions(permissions, REQUEST_PERMISSION_CAMERA_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CAMERA_CODE) {
            int grantResult = grantResults[0];
            boolean granted = grantResult == PackageManager.PERMISSION_GRANTED;
            Log.i("====", "onRequestPermissionsResult granted=" + granted);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);


        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            int i = ContextCompat.checkSelfPermission(this, permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (i != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                requestCameraPermission();
            }
        }


        initView();
        startService(new Intent(MainActivity.this, MyServerSocketService.class));
//        创建定时器
        timerTask();

//
//        Intent intent = new Intent(this, VideoActivity.class);
//        startActivity(intent);

    }

    TimerTask task = new TimerTask() {
        public void run() {
            Message message = new Message();
            message.what = HANDLER_MSG_UPDATE;
            mHandler.sendMessage(message);
        }
    };

    private void timerTask() {
        //创建定时线程执行更新任务
        mTimer.schedule(task, 60 * 1000, 60 * 1000);// 定时任务
    }

    private void initView() {
        tianqiTv = (TextView) findViewById(R.id.tianqi_tv);
        timeMdTv = ((TextView) findViewById(R.id.time_md_tv));
        timeHhTv = ((TextView) findViewById(R.id.time_hh_tv));
        timeMmTv = ((TextView) findViewById(R.id.time_mm_tv));
        weekTv = ((TextView) findViewById(R.id.week_tv));
        nongLiTv = ((TextView) findViewById(R.id.nongli_tv));
        helloworldTv = ((TextView) findViewById(R.id.helloworld_tv));
        weatherImg = ((ImageView) findViewById(R.id.weather_img));
        setDate();
//        findViewById(R.id)
    }

    private void setDate() {
        currentTime = System.currentTimeMillis();
                /*todo MobAPI 对象获取*/
        Weather api = (Weather) MobAPI.getAPI(Weather.NAME);
        api.queryByCityName("青岛", this);//TODO 设置查询地区
        calendarApi = ResHelper.forceCast(MobAPI.getAPI(com.mob.mobapi.apis.Calendar.NAME));
        String date = MyDateUtil.changeYMD(currentTime);
        calendarApi.queryCalendar(date, this);

        Log.e(TAG, "setDate: " + api.toString() + "///////" + calendarApi.toString());

        timeMdTv.setText(MyDateUtil.changeMD(currentTime));//设置月日
        String newH = MyDateUtil.changeH(currentTime);
        nowHInt = Integer.parseInt(newH);
        timeHhTv.setText(newH);//设置小时
        timeMmTv.setText(MyDateUtil.changem(currentTime));//设置分钟
        Calendar rightNow = Calendar.getInstance();
        int week = rightNow.get(rightNow.DAY_OF_WEEK) - 1;
        weekTv.setText("周" + MyDateUtil.week[week]);

        if (nowHInt <= 10 && nowHInt >= 5) {
            helloworldTv.setText("早上好");
        } else if (nowHInt >= 18 && nowHInt <= 20) {
            helloworldTv.setText("晚上好");
        } else {
            helloworldTv.setText("你好");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        requestCameraPermission();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (mTimer != null) {// 停止timer
            mTimer.cancel();
            mTimer = null;
        }
        EventBus.getDefault().unregister(this);

    }

    @Override
    public void readSuccess(String text) {
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        Toast.makeText(MainActivity.this, event.getMsg(), Toast.LENGTH_SHORT).show();
        if (event.getType() == Contance.READSUCCESS) {
            if (event.getMsg().equals(Contance.OPEN_CAMERA)) {
                /*打开相机成功，然后进入到qrlibrary中的CaptureActivity*/
                Intent intent = new Intent(this, CaptureActivity.class);
                intent.putExtra("type", "openCamera");
                startActivity(intent);
            }
            if (event.getMsg().equals(Contance.OPEN_VIDEO)) {
                /*打开相机成功，然后进入到qrlibrary中的CaptureActivity*/
                Intent intent = new Intent(this, CaptureActivity.class);
                startActivity(intent);
            }
//            if (event.getMsg().equals(Contance.TAKE_PIC)) {
//                Toast.makeText(MainActivity.this, "拍照", Toast.LENGTH_SHORT).show();
////                Log.e("====", "onMessageEvent: " + Contance.TAKE_PIC + "拍照");
////                EventBus.getDefault().post(new MessageEvent(event.getMsg(), Contance.CONTROLCAP));
//            }

        }
    }

    /**
     * MobSDK 网络请求成功回调
     */
    @Override
    public void onSuccess(API api, int i, Map<String, Object> map) {
        switch (i) {
            case Weather.ACTION_CITYS:
                break;
            case Weather.ACTION_QUERY:
                if (api.equals(this.calendarApi)) {
                    //农历详情
                    HashMap<String, Object> res = ResHelper.forceCast(map.get("result"));
                    nongLiTv.setText(com.mob.tools.utils.ResHelper.toString(res.get("lunar")));
                } else {
                    //获取天气信息
                    ArrayList<HashMap<String, Object>> results = (ArrayList<HashMap<String, Object>>) map.get("result");
                    HashMap<String, Object> weather = results.get(0);
                    String weather1 = ResHelper.toString(weather.get("weather"));
                    String updateTime = ResHelper.toString(weather.get("updateTime"));
                    Log.e(TAG, "onSuccess: ---" + updateTime);
                    tianqiTv.setText(weather1);
//TODO 设置天气图标
                    HashMap hashMap = setWeather2UI();
                    boolean b = hashMap.containsKey(weather1);
                    int resMipmap = (int) hashMap.get(weather1);
                    weatherImg.setBackground(this.getResources().getDrawable(resMipmap));

                }
                break;
        }
    }

    private HashMap setWeather2UI() {
        HashMap<String, Integer> hashMap = new HashMap<>();
//                    hashMap.put("", 1);

        String[] s = {"晴", "少云", "多云", "零散阵雨", "小雨", "中雨", "阵雨", "零散雷雨", "雨夹雪", "雷阵雨", "小雪", "霾", "雨", "阵雪", "阴",};
        int[] ints = {R.mipmap.w_1,
                R.mipmap.w_2,
                R.mipmap.w_3,
                R.mipmap.w_4,
                R.mipmap.w_5,
                R.mipmap.w_6,
                R.mipmap.w_7,
                R.mipmap.w_8,
                R.mipmap.w_9,
                R.mipmap.w_10,
                R.mipmap.w_11,
                R.mipmap.w_12,
                R.mipmap.w_13,
                R.mipmap.w_11,
                R.mipmap.w_3};
        for (int j = 0; j < s.length; j++) {
            hashMap.put(s[j], ints[j]);
        }
        return hashMap;
    }

    /**
     * MobSDK 网络请求失败回调
     */
    @Override
    public void onError(API api, int i, Throwable throwable) {
        throwable.printStackTrace();
        Toast.makeText(this, "发现异常，请查看Logcat！", Toast.LENGTH_SHORT).show();
    }
}
